from urllib.request import Request
from http.client import HTTPResponse

from .liteTool import firefox_cookie, my_urlopen

import json
import gzip
import datetime


def get_video_list_from_uploader_id(uid: str, start_time: datetime.datetime, end_time: datetime.datetime) -> list:

    def __get_video_list_in_json(url: str, header: dict, method: str) -> list:
        print('获取视频投稿列表：' + url)
        try:
            request = Request(url=url, headers=header, method=method)
            response = my_urlopen(url=request)  # type: HTTPResponse
            video_list_str = gzip.decompress(response.read()).decode(encoding='utf-8')
            video_list_json = json.loads(video_list_str)
            return video_list_json['data']['list']['vlist']
        except Exception as e:
            print(e)
            return []

    if start_time > end_time:
        start_time, end_time = end_time, start_time

    page_capacity = 30
    page_index = 1
    finish = False
    results = []

    while not finish:
        """
        mid:     用户的数字ID
        ps:      一页放几个视频
        tid:     视频分类信息
        pn:      要获取第几页视频
        keyword: 搜索关键字
        order:   按什么排序
        """
        video_url = 'https://api.bilibili.com/x/space/arc/search?' + \
                    f'mid={uid}&ps={page_capacity}&tid=0&pn={page_index}&keyword=&order=pubdate&jsonp=jsonp'
        video_header = {
            'Host': 'api.bilibili.com',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0',
            'Accept': 'application/json, text/plain, */*',
            'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
            'Accept-Encoding': 'gzip, deflate, br',
            'Origin': 'https://space.bilibili.com',
            'Connection': 'keep-alive',
            'Referer': f'https://space.bilibili.com/{uid}/video?tid=0&page={page_index}&keyword=&order=pubdate',
            'Cookie': firefox_cookie,
            'TE': 'Trailers',
        }

        videos = __get_video_list_in_json(url=video_url, header=video_header, method='GET')

        if videos is None or len(videos) == 0:
            break

        for v in videos:  # type: dict
            time_stamp = int(v.get('created'))
            upload_time = datetime.datetime.fromtimestamp(time_stamp)

            if start_time <= upload_time <= end_time:
                results.append(v)

            if upload_time < start_time:
                finish = True
                break
        page_index += 1

    return results


if __name__ == '__main__':
    pass
    # begin = datetime.datetime(year=2020, month=5, day=30, hour=23, minute=59, second=59)
    # end = datetime.datetime(year=2020, month=1, day=1, hour=0, minute=0, second=0)
    # res = get_video_list_from_uploader_id(uid='10330740', start_time=begin, end_time=end)
    #
    # print(f'共找到 {len(res)} 个结果。\n')
    # with open(file='D:/MyResources/爬虫数据/哔哩哔哩干杯/观察者网.json', mode='w', encoding='utf-8') as f:
    #     j = json.dumps(res, ensure_ascii=False)
    #     f.write(j)
    # for v in res:
    #     created = datetime.datetime.fromtimestamp(v['created'])
    #     print(v['title'])
    #     print(created)
    #     print(v['aid'])
    #     print(v['bvid'])
    #     print()
